<template>
    <div>
         <!--  面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col><el-button type="primary" @click="showAddRoleDialog">添加角色</el-button></el-col>
            </el-row>
            <el-table :data="rolesList" stripe border>
                <!-- 展开 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bd-bottom','vcenter', i1 == 0?'bd-top':'']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限-->
                            <el-col :span="5">
                                <el-tag
                                closable
                                @close="removeRightById(scope.row,item1.id)">{{item1.name}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限-->
                            <el-col :span="19">
                                <el-row :class="[i2 == 0?'':'bd-top','vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                                    <!-- 渲染一级权限-->
                                    <el-col :span="6">
                                        <el-tag
                                        type="success"
                                         closable
                                         @close="removeRightById(scope.row,item2.id)">{{item2.name}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning"
                                        v-for="item3 in item2.children"
                                        :key="item3.id"
                                        closable
                                        @close="removeRightById(scope.row,item3.id)">{{item3.name}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="des" label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showAddRoleDialog(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-edit" @click="removeRoleByid(scope.row.id)">删除</el-button>
                        <el-button type="warning" size="mini" icon="el-icon-edit" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限对话框 -->
        <el-dialog
          title="分配权限"
          :visible.sync="setRightDialogVisible"
          width="50%" @close="setRightDialogClosed">
          <el-tree
           ref="treeRef"
           :data="rightsList"
           :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="defaultKeys"
            default-expand-all></el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 添加用户的对话框 -->
        <el-dialog
          title="添加角色"
          :visible.sync="addRoleVisible"
          width="50%"
          @close="addRoleDialogClosed">
          <el-form ref="addRoleRef" :model="addRole" :rules="addRoleRules" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addRole.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDes">
              <el-input v-model="addRole.roleDes"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrEditRole">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
import { roles, deleteRightOfRole, rights, allotRights, addOrEditRole, deleteRole } from '../../api/user'
export default {
  data () {
    return {
      rolesList: [],
      setRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      defaultKeys: [],
      roleId: '',
      addRoleVisible: false,
      // 添加角色表单数据
      addRole: {
        roleName: '',
        roleDes: ''
      },
      // 添加角色表单的验证规则对象
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDes: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    getRolesList () {
      roles().then(response => {
        const { data } = response
        this.rolesList = data.data
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    // 根据id删除对应的权限
    async removeRightById (role, id) {
      const confirmResult = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      console.log(confirmResult)
      // 确定返回confirm，取消返回 cancel
      if (confirmResult === 'confirm') {
        deleteRightOfRole(role.id, id).then(response => {
          const { data } = response
          role.children = data.data
          this.$message.success('权限删除成功')
        }).catch(error => {
          this.$message.error(error.message)
        })
      }
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      rights('tree').then(response => {
        const { data } = response
        this.rightsList = data.data
        this.getLeafKeys(role, this.defaultKeys)
        this.setRightDialogVisible = true
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    // 通过递归的形式，获取角色下三级的id，并保存到defautkeys数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightDialogClosed () {
      this.defaultKeys = []
    },
    allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      allotRights(this.roleId, { ids: idStr }).then(response => {
        this.getRolesList()
        this.$message.success('权限分配成功')
        this.setRightDialogVisible = false
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    showAddRoleDialog (role) {
      this.roleId = ''
      if (role) {
        this.roleId = role.id
        this.addRole.roleName = role.roleName
        this.addRole.roleDes = role.des
      }

      this.addRoleVisible = true
    },
    addRoleDialogClosed () {
      this.$refs.addRoleRef.resetFields()
    },
    addOrEditRole () {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        addOrEditRole({
          id: this.roleId,
          roleName: this.addRole.roleName,
          roleDes: this.addRole.roleDes
        }).then(response => {
          const { data } = response
          this.$message.success(data.msg)
          this.addRoleVisible = false
          this.getRolesList()
        }).catch(error => {
          this.$message.error(error.message)
        })
      })
    },
    async removeRoleByid (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      console.log(confirmResult)
      // 确定返回confirm，取消返回 cancel
      if (confirmResult === 'confirm') {
        deleteRole(id).then(response => {
          this.$message.success('角色删除成功')
          this.getRolesList()
        }).catch(error => {
          this.$message.error(error.message)
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
    border-top: 1px solid #eee;
}

.bd-bottom {
    border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
